package com.leanit.pmc.center.enterprise;

import com.leanit.pmc.center.user.UserInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;

/**
 * 企业管理Controller
 */
@Controller
@RequestMapping("enterprise")
@Scope("prototype")
public class EnterpriseController {

    private final org.slf4j.Logger logger = LoggerFactory.getLogger(EnterpriseController.class);

    @Autowired
    private EnterpriseService enterpriseService;

    /**
     * 跳转企业信息管理页面
     *
     * @param map
     * @return
     */
    @RequestMapping(value = "enterpriseInformation", method = RequestMethod.GET)
    public String enterpriseInformation(ModelMap map, HttpSession session) {
        UserInfo userInfo = (UserInfo) session.getAttribute("UserInfo");
        //此处获取session里面UserInfo中organizationCode
        map.addAttribute("enterPriseInfo", enterpriseService.getEnterpriseInfo(userInfo.getOrganizationCode()));
        return "center/enterprise/enterprise_information";
    }

    /**
     * 企业信息完善表单提交
     *
     * @param enterPriseInfo
     * @return
     */
    @RequestMapping(value = "/updateEnterpriseInfo")
    public String upload(EnterPriseInfo enterPriseInfo, ModelMap map) {
        String errorMsg = "";
        MultipartFile organizationLicense = enterPriseInfo.getOrganizationLicense();
        MultipartFile taxLicense = enterPriseInfo.getTaxLicense();
        MultipartFile businessLicense = enterPriseInfo.getBusinessLicense();

        if (organizationLicense != null && organizationLicense.getSize() > 2097152) {
            errorMsg += "组织机构代码证超过大小限制，请重新选择；";
        }
        if (taxLicense != null && taxLicense.getSize() > 2097152) {
            errorMsg += "税务登记证超过大小限制，请重新选择；";
        }
        if (businessLicense != null && businessLicense.getSize() > 2097152) {
            errorMsg += "营业执照超过大小限制，请重新选择；";
        }

        if (StringUtils.isNotEmpty(errorMsg)) {
            map.addAttribute("errorMsg", errorMsg);
        } else {
            try {
                if (organizationLicense != null) {
                    enterPriseInfo.setOrganizationBlob(inputStreamToByte(organizationLicense.getInputStream()));
                    enterPriseInfo.setOrganizationName(new String(organizationLicense.getOriginalFilename().getBytes("ISO8859-1"), "UTF-8"));
                }

                if (taxLicense != null) {
                    enterPriseInfo.setTaxBlob(inputStreamToByte(taxLicense.getInputStream()));
                    enterPriseInfo.setTaxName(new String(taxLicense.getOriginalFilename().getBytes("ISO8859-1"), "UTF-8"));
                }

                if (businessLicense != null) {
                    enterPriseInfo.setBusinessBlob(inputStreamToByte(businessLicense.getInputStream()));
                    enterPriseInfo.setBusinessName(new String(businessLicense.getOriginalFilename().getBytes("ISO8859-1"), "UTF-8"));
                }

                if (enterpriseService.updateEnterpriseInfo(enterPriseInfo)) {
                    map.addAttribute("status", 1);
                }
            } catch (IOException e) {
                map.addAttribute("status", 0);
                map.addAttribute("errorMsg", e.toString());
                logger.error("IOException===", e);
            }
        }
        map.addAttribute("enterPriseInfo", enterpriseService.getEnterpriseInfo(enterPriseInfo.getOrganizationId()));
        return "center/enterprise/enterprise_information";
    }

    /**
     * 下载三证信息
     *
     * @param response
     * @param enterPriseInfo
     */
    @RequestMapping(value = "/download")
    public void download(HttpServletResponse response, EnterPriseInfo enterPriseInfo, String type) {
        enterPriseInfo = enterpriseService.getBusinessBlob(enterPriseInfo.getId(), type);
        downloadFile(enterPriseInfo.getBusinessName(), response, enterPriseInfo.getBusinessBlob());
    }

    /**
     * 将输入流转成字数组
     *
     * @param is
     * @return
     * @throws IOException
     */
    private byte[] inputStreamToByte(InputStream is) throws IOException {
        ByteArrayOutputStream bAOutputStream = new ByteArrayOutputStream();
        int ch;
        while ((ch = is.read()) != -1) {
            bAOutputStream.write(ch);
        }
        byte data[] = bAOutputStream.toByteArray();
        bAOutputStream.close();
        return data;
    }

    /**
     * 推送到页面，弹出下载窗口
     *
     * @param fileName
     * @param response
     * @param content
     */
    private void downloadFile(String fileName, HttpServletResponse response, byte[] content) {
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            InputStream is = new ByteArrayInputStream(content);
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));
            ServletOutputStream out = response.getOutputStream();
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
        } catch (UnsupportedEncodingException e) {
            logger.error("UnsupportedEncodingException===", e);
        } catch (IOException e) {
            logger.error("IOException===", e);
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                    if (bos != null) {
                        bos.close();
                    }
                } catch (IOException e) {
                    logger.error("IOException===", e);
                }
            }
        }
    }

}
